package com.donggua.client.fileserverlibrary;

import android.app.Activity;
import android.util.Log;

import com.dg.acb.utils.configdata.DGConfigData;
import com.dg.acb.utils.configdata.XXConstants;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGNetUtil;
import com.xx.xiawan.net.DGRequestListener;
import com.xx.xiawan.net.GetRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;


public class FileServerUpload {
    private UploadManager uploadManager;
    private long uploadLastTimePoint;
    private long uploadLastOffset;
    private long uploadFileLength;
    private Activity act;
    private DGConfigData dgConfigData;

    IUploadComplete mUploadComplete = null;
    IUploadProgress mUploadProgress = null;

    public interface IUploadComplete {
        public void onUploadSuccess(String fileKey, String fileHash, int code);
        public void onUploadFail(String errorMsg, int code);
    }

    public interface IUploadProgress {
        public void updateStatus(String Key,final double percentage, int code) ;
    }


    public void setOnUploadSuccess(IUploadComplete iUploadComplete) {
        mUploadComplete = iUploadComplete;
    }
    public void setOnUploadProgress(IUploadProgress iUploadProgress) {
        mUploadProgress = iUploadProgress;
    }

    public FileServerUpload(Activity act) {
        this.act = act;
        dgConfigData = new DGConfigData(act);
    }

    private String getToken(String url,String login_token) {

        GetRequest getRequest = new GetRequest(url, act);
        getRequest.header("token", login_token);
        DGJsonResult res = getRequest.start();
        if (res != null && res.result != null) {
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(res.result);
                String token = jsonObject.getString("token");
                Log.i("drj", "token res.result" + res.result);
                return token == null ? "" : token;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return "";
    }

    public void uploadPublic(final String filePath, final int code, final String login_token) {
        DGRequestListener listener = new DGRequestListener() {
            @Override
            public void onSuccess(DGJsonResult result) {
                if(result.errorCode == DGNetUtil.REQUEST_NEED_LOGIN){
                    if(mUploadComplete != null){
                        mUploadComplete.onUploadFail(result.errorMsg,result.errorCode);
                    }
                }else{
                    try {
                        JSONObject object = new JSONObject(result.result);
                        String token = object.getString("token");
                        upload(filePath, token, code);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String error) {

            }
        };
        GetRequest getRequest = new GetRequest(XXConstants.URI_UPLOAD_TOKEN_PUBLIC, act,listener);
        getRequest.header("token", login_token);
        getRequest.startNoLock();

        /*
        new Thread(new Runnable() {
            @Override
            public void run() {
                String uploadToken;
                uploadToken = getToken(XXConstants.URI_UPLOAD_TOKEN_PUBLIC,login_token);
                Log.i("drj", "uploadToken: " + uploadToken+" loginToken is "+login_token);
                if (uploadToken.length() > 0) {
                    upload(filePath, uploadToken, code);
                }else {
                    mUploadComplete.onUploadFail("文件服务器连接失败！",code);
                }
            }
        }).start();*/
    }

    public void uploadPrivate(final String filePath, final int code, final String login_token) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String uploadToken;
                uploadToken = getToken(XXConstants.URI_UPLOAD_TOKEN_PRIVATE,login_token);
                Log.i("drj", "uploadToken:" + uploadToken);
                if (uploadToken.length() > 0) {
                    upload(filePath, uploadToken, code);
                }else {
                    mUploadComplete.onUploadFail("文件服务器连接失败！",code);
                }
            }
        }).start();
    }

    private void upload(String filePath, String uploadToken, final int code) {
        if (this.uploadManager == null) {
            this.uploadManager = new UploadManager();
        }
        File uploadFile = new File(filePath);
        UploadOptions uploadOptions = new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    @Override
                    public void progress(String key, double percent) {
                        updateStatus(percent);
                        if (mUploadProgress != null){
                            mUploadProgress.updateStatus(key,percent,code);
                        }
                    }
                }, null);
        final long startTime = System.currentTimeMillis();
        final long fileLength = uploadFile.length();
        this.uploadFileLength = fileLength;
        this.uploadLastTimePoint = startTime;
        this.uploadLastOffset = 0;

        AsyncRun.runInMain(new Runnable() {
            @Override
            public void run() {

            }
        });

        this.uploadManager.put(uploadFile, null, uploadToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo,
                                         JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                String fileKey = jsonData.getString("key");
                                String fileHash = jsonData.getString("hash");
                                mUploadComplete.onUploadSuccess(fileKey, fileHash, code);
                            } catch (JSONException e) {
                                mUploadComplete.onUploadFail("文件服务器上传回复解析错误！",code);

                                if (jsonData != null) {
                                    Log.i("Test", jsonData.toString());
                                }
                            }
                        } else {
                            mUploadComplete.onUploadFail("文件服务器上传文件失败！",code);

                            Log.i("Test", respInfo.toString());
                            if (jsonData != null) {
                                Log.i("Test", jsonData.toString());
                            }
                        }
                    }

                }, uploadOptions);
    }

    private void updateStatus(final double percentage) {
        long now = System.currentTimeMillis();
        long deltaTime = now - uploadLastTimePoint;
        long currentOffset = (long) (percentage * uploadFileLength);
        long deltaSize = currentOffset - uploadLastOffset;
        if (deltaTime <= 100) {
            return;
        }

        final String speed = Tools.formatSpeed(deltaSize, deltaTime);
        // update
        uploadLastTimePoint = now;
        uploadLastOffset = currentOffset;

        AsyncRun.runInMain(new Runnable() {
            @Override
            public void run() {
                int progress = (int) (percentage * 100);
            }
        });
    }

}
